import React, { useEffect, useRef, useState } from "react";
import {
  Space,
  Table,
  Tag,
  Button,
  Modal,
  Form,
  Input,
  Select,
  FormInstance,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { addAdmin, getAdminList } from "@/api/user";
import TableTop from "@/components/table-top";
import UserMenuModal from "./user-menu-modal";

const User: React.FC = () => {
  const columns: ColumnsType<AdminInfo2> = [
    {
      title: "管理员姓名",
      dataIndex: "adminname",
    },
    {
      title: "管理员角色",
      dataIndex: "role",
      render: (col, row: any) => {
        let color = row.role === 1 ? "geekblue" : "green";
        let text = row.role === 1 ? "管理员" : "超级管理员";
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "操作",
      dataIndex: "role",
      render: (col, row) => {
        return (
          <Space>
            <Button
              onClick={() => {
                (menuModalRef.current as any).openModal(row);
              }}
            >
              设置权限
            </Button>
            <Button>删除</Button>
          </Space>
        );
      },
    },
  ];
  // 表格行数据
  const [rows, setRows] = useState<AdminInfo2[]>([]);

  // 控制添加管理员Modal
  const [showAdd, setShowAdd] = useState(false);
  const addFormRef = useRef<FormInstance>(null);
  const onAddOk = async () => {
    // 获取到表单输入的数据
    //  !. 非空断言，要区别于 ?.
    // console.log(addFormRef.current!.getFieldsValue());
    const params = addFormRef.current!.getFieldsValue();
    // 调用接口
    await addAdmin(params.username, params.password, params.role);
    message.success("添加成功");
    // 关闭Modal
    setShowAdd(false);
    // 重新获取下列表数据
    fetchData();
  };
  const onAddCancel = () => {
    // 直接将 showAdd 设置为false
    setShowAdd(false);
  };

  // menuModal
  const menuModalRef = useRef(null);

  async function fetchData() {
    const res = await getAdminList();
    // PS: 由于utils/request.ts 中统一处理了业务状态码的判断，这里可以不用判断了
    // 设置表格的行数据
    setRows(res.data!);
  }

  useEffect(() => {
    fetchData();
  }, []);

  // 报错 Each child in a list should have a unique "key" prop.
  //      设置 rowKey
  return (
    <Space direction="vertical" style={{ display: "flex" }}>
      <TableTop>
        <Button
          onClick={() => {
            setShowAdd(true);
          }}
        >
          添加管理员
        </Button>
      </TableTop>

      <Table
        rowKey="_id"
        columns={columns}
        dataSource={rows}
        pagination={false}
      />

      <Modal
        title="添加管理员"
        open={showAdd}
        onOk={onAddOk}
        onCancel={onAddCancel}
      >
        <Form ref={addFormRef} initialValues={{ role: 1 }}>
          <Form.Item label="管理员姓名" name="username">
            <Input />
          </Form.Item>
          <Form.Item label="管理员密码" name="password">
            <Input />
          </Form.Item>
          <Form.Item label="管理员角色" name="role">
            <Select>
              <Select.Option value={1}>管理员</Select.Option>
              <Select.Option value={2}>超级管理员</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      <UserMenuModal
        ref={menuModalRef}
        onOk={() => {
          fetchData();
        }}
      />
    </Space>
  );
};

export default User;
